package com.dongdong.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dongdong.result.Result;
import com.dongdong.vo.RefundQueryVO;
import com.dongdong.vo.RefundVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("pay")
public class PaysController {

@Autowired
private AlipayClient alipayClient;


    @GetMapping("/aliPay")
    public String aliPay(@RequestParam String out_trade_no, @RequestParam String total_amount , @RequestParam String subject){
//        https://5f3d97b0.r29.cpolar.top/pay/aliPay?out_trade_no=10000001&total_amount=2&subject=袜子

/*        AlipayClient alipayClient = new DefaultAlipayClient(
//                "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
//                "9021000134692508",
//                "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCJL1CHX6xy2HS4Nbzfq+u0FoI5WfJwLP4evfCMPi0hiT36+JzDcYc9oFLvmllFWNCtx2RjWpLJUfvCobv9pDwXS0xQ37iBGDdIBWZ5NEnbLXEgd3jBB5B80sfKRY59HDTcUVi+nJojV0CQMcFct9dBI2GEYhlDpjqP9VkDdkr3N4nWgdGJtm3JpCCiLTw6xeZZ+zc5KR0OycO8UmfLWBMf1v0fLVW9PFZLzbX0QIime2BKhaaX/8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4GWy8juZVC/9ipCeoW+GyZLJsUQWNAVDjyDnAI+OoSIB6esnfTStSbsCGyAut92P0yCqSGKx5BkCgYA2cGl6wrYUNTEPynTKxEfqvtfHAXUX4299kIkozkCWQ4j2P2yFmy0CZ/gL5LSv2mkgZMfYZwLX9aTnJa2OJb2Ge1QHDphezTsPJzAEZgbSixVRFKcYZyuBDf16xg3RP/a6wdJma94zltX3QROssL/91VOH0f+bKMcp4z+TW/rqzA==",
//                "json",
//                "UTF-8",
//                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi4zPLYJ/hdYYErpd8XKqVu931D6RTfC5pWeATOiGRz1IG2WOoJ+pXCKsAFRynpIwnUoDYKMb8yyvbRHIKJnaRu/HIwaZ1LrjNs9BUBgMXcMpt9xNrZm8uryTJncdtL909TKyVAtvC+NzMclSGe4go52vV9gq46tnhZTStdM3QjtwbGyKbosvbVxZYKJNTEVx7dy88nl26OeCKv8BncWa2dkcT/zJWTy70DCcy4ZhZRbiNU9GNj1kjImwl1Ax7tVP1Egg+YWYtaSJGuvjnbgxqCSGC40LnqazGxVUY7tG6ULGQLTXeLx+Ku6qP6h5z0xqm64eXc153TX75fwqVraZxwIDAQAB",
//                "RSA2");
                serverUrl,
                appId,
                privateKey,
                format,
                charset,
                alipayPublicKey,
                signType);*/

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        request.setNotifyUrl("http://4a51b5ac.r17.cpolar.top/ny/notifyUrl");//异步接收地址，仅支持http/https，公网可访问  post请求  通过这个回调就可以使用异步的方式知道是否支付成功
//        request.setReturnUrl("http://4a51b5ac.r17.cpolar.top/ny/returnUrl");//同步跳转地址，仅支持http/https              get请求    // 当调用支付宝支付接口成功后 默认定位在的是支付宝成功页面 需要跳转到商家页面 这个时候不能保证真的支付成功
        request.setNotifyUrl("http://451c8f2a.r8.cpolar.top/ny/notifyUrl");//异步接收地址，仅支持http/https，公网可访问  post请求  通过这个回调就可以使用异步的方式知道是否支付成功
        request.setReturnUrl("http://451c8f2a.r8.cpolar.top/ny/returnUrl");//同步跳转地址，仅支持http/https              get请求    // 当调用支付宝支付接口成功后 默认定位在的是支付宝成功页面 需要跳转到商家页面 这个时候不能保证真的支付成功

/******必传参数******/
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);//商户订单号，商家自定义，保持唯一性
        bizContent.put("total_amount", total_amount);//支付金额，最小值0.01元
        bizContent.put("subject", subject);//订单标题，不可使用特殊符号
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request,"POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
// 如果需要返回GET请求，请使用
// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }



    //支付查询接口
    @GetMapping("tradeQuery")
    public Result tradeQuery(@RequestParam String tradeNo) {

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("trade_no",tradeNo);
        request.setBizContent (JSONObject.toJSONString(jsonObject));
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return Result.OK().setData(response.getBody());
    }


    //退款接口
    @GetMapping("/tradeRefund")
    // SpringMVC
    public Result tradeRefund(@RequestParam String tradeNo,@RequestParam String refundAmount,@RequestParam String outRequestNo){

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);


        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body); //转型
            Object alipay_trade_refund_response = jsonObject.get("alipay_trade_refund_response");

            String s = JSONObject.toJSONString(alipay_trade_refund_response); //转成bean
            RefundVO refundVO = JSONObject.parseObject(s, RefundVO.class);  //赋值
            //判断
            if (! Objects.equals(refundVO.getFund_change(), "Y")) {
                //调用退款查询接口
                RefundQueryVO refundQueryVO = getRefundVO(tradeNo, outRequestNo);
                if (Objects.equals(refundQueryVO.getRefund_status(), "REFUND_SUCCESS")) {
                    return Result.OK().setData("相同请求号不能二次退款");
                } else {
                    return Result.OK().setData("退款失败");
                }
            }else {
                return Result.OK().setData("退款成功");
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    //退款2
    @GetMapping("refundQuery")
    public String refundQuery(@RequestParam String tradeNo,@RequestParam String refundAmount,@RequestParam String outRequestNo){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body); //转型
            Object alipay_trade_refund_response = jsonObject.get("alipay_trade_refund_response");

            String s = JSONObject.toJSONString(alipay_trade_refund_response); //转成bean
            RefundVO refundVO = JSONObject.parseObject(s, RefundVO.class);  //赋值
            //判断
            if (! Objects.equals(refundVO.getFund_change(), "Y")) {
                //调用退款查询接口
                RefundQueryVO refundQueryVO = getRefundVO(tradeNo, outRequestNo);
                if (Objects.equals(refundQueryVO.getRefund_status(), "REFUND_SUCCESS")) {
                    return "相同请求号不能二次退款";
                }else {
                    return "退款失败";
                }
            }else {
                return "退款成功";
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

//退款查询接口
    public RefundQueryVO getRefundVO(String tradeNo, String outRequestNo){

        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("out_request_no", outRequestNo);


        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object alipay_trade_fastpay_refund_query_response = jsonObject.get("alipay_trade_fastpay_refund_query_response");
            String s = JSONObject.toJSONString(alipay_trade_fastpay_refund_query_response);
            RefundQueryVO refundQueryVO = JSONObject.parseObject(s, RefundQueryVO.class);
            return refundQueryVO;

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }





















}
